import { loginByUsername, logout, getUserInfo, getOAuthTokeByCode, getUserDetailInfo } from '@/api/login';
import { getToken, setToken, removeToken, setUserName, removeUserName } from '@/utils/auth';
import { queryCurrenDmDeptInfo } from '@/api/common';

const { getSetting, getSettingBool } = window.systemParamsUtils;
const user = {
  state: {
    user: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    permissions: [],
    info: {},
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_INFO: (state, info) => {
      state.info = info;
    },
    SET_DEPT: (state, dept) => {
      state.info.dept = dept;
    },
    SET_CODE: (state, code) => {
      state.code = code;
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction;
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting;
    },
    SET_STATUS: (state, status) => {
      state.status = status;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password)
          .then(({ data }) => {
            setUserName(data.name);
            commit('SET_NAME', data.name);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        let params = {};
        if (getSettingBool('IS_OAUTH2')) {
          params['access_token'] = getToken();
          params['appCode'] = getSetting('APP_CODE');
        }
        getUserInfo(params)
          .then(({ data: info }) => {
            if (info.name === undefined) {
              reject(info);
            }
            getUserDetailInfo().then(({ data }) => {
              if (!data.baseUserInfo) {
                reject(data);
              }
              // deptName 为单位名称，baseUserInfo 是框架内置类后端不好加在里面，前端组合以便使用
              const { baseUserInfo, deptName, rightList } = data;
              let permissions = [];
              if (rightList.length) {
                permissions = rightList.map(item => item.id);
              }
              if (baseUserInfo.name === undefined) {
                reject(data);
              } else {
                commit('SET_INFO', { ...baseUserInfo, deptName });
                commit('SET_NAME', baseUserInfo.name);
                commit('SET_PERMISSIONS', permissions);
                commit('SET_AVATAR', data.avatar);
                setUserName(data.name);
                resolve(data);
              }
              console.log('userinfo', baseUserInfo);
            });
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 获取当前登录用户所在单位的信息
    QueryCurrenDmDeptInfo({ commit }) {
      return new Promise((resolve, reject) => {
        queryCurrenDmDeptInfo()
          .then(res => {
            let dept = res.data.YWJZ;
            commit('SET_DEPT', dept);
            resolve(dept);
          })
          .catch(error => {
            reject(error);
          });
      });
      
    },

    // oauth2登录方式获取token
    GetOAuthToken({ commit }, param) {
      return new Promise((resolve, reject) => {
        let params = {
          grant_type: 'authorization_code',
          code: param.code,
          redirect_uri: location.href.split('?')[0],
          client_id: getSetting('CLIENT_ID'),
          client_secret: getSetting('CLIENT_SECRET')
        };
        getOAuthTokeByCode(params)
          .then(({ data }) => {
            commit('SET_TOKEN', data.access_token);
            setToken(data.access_token);
            resolve(param.code);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 登出
    Logout({ commit }) {
      return logout({ redirectUrl: location.href }).then(() => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        removeToken();
        removeUserName();
      });
    },

    // oauth2登录方式退出
    LogoutOauth({ commit }, logoutUrl) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_NAME', '');
        removeToken();
        removeUserName();
        resolve();
        window.location.href = logoutUrl;
      });
    },

    // 前端 登出
    FedLogout({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_NAME', '');
        removeToken();
        removeUserName();
        resolve();
      });
    }
  }
};

export default user;
